<template>
    <div class="login-container">

        <el-form :model="loginForm" :rules="rules"
                 status-icon
                 ref="loginForm"
                 label-position="left"
                 label-width="0px"
                 class="demo-ruleForm login-page">
<!--            <el-page-header @back="goBack" content="">
            </el-page-header>-->

            <h2 class="title_1">欢迎登录</h2>
            <h5 class="title_2">Welcome to Login...</h5>
            <!-- <el-form-item></el-form-item>
            <el-form-item></el-form-item>
            <el-form-item></el-form-item>
            <el-form-item></el-form-item>
            <el-form-item></el-form-item>
            <el-form-item></el-form-item>
            <el-form-item></el-form-item>
            <el-form-item></el-form-item>
            <el-form-item></el-form-item> -->
            <div class="loginform">
            <el-form-item prop="userAccount">
                <el-input type="text"
                          v-model="loginForm.userAccount"
                          auto-complete="off"
                          placeholder="请输入用户名"
                ></el-input>
            </el-form-item>
            <el-form-item prop="userPassword">
                <el-input type="password"
                          v-model="loginForm.userPassword"
                          auto-complete="off"
                          placeholder="请输入密码"
                          show-password
                ></el-input>
            </el-form-item>
            <el-checkbox v-model="checked" class="rememberme">记住密码</el-checkbox>
            <el-form-item style="width:100%;">
                <el-button type="primary" style="width:100%;margin-top: 15px;" @click="submit">登录</el-button>
            </el-form-item>
            <el-divider content-position="center">or</el-divider>
            <el-form-item style="width:100%;">
                <el-button style="width:100%;" @click="cancel">取消</el-button>
            </el-form-item>
            </div>
        </el-form>
        <van-dialog v-model="confirmInfo" :before-close="onBeforeClose">
            <van-cell class="userinfo" title="姓名:" :value="user_name" />
            <van-cell class="userinfo" title="学号:" :value="user_number" />
        </van-dialog>
    </div>
</template>

<script>
    import { isVisitorLogin } from '../../network/request';
    import storage from "../../model/storage";
    import { Notify, Toast  } from 'vant';

    export default {
        name: "Login",
        data() {
            const checkSpecificKey = str => {
              var specialKey =
                "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'";
              for (var i = 0; i < str.length; i++) {
                if (specialKey.indexOf(str.substr(i, 1)) != -1) {
                  return false;
                }
              }
              return true;
            };
            const pass = (rule, value, callback) => {
              //rule是传入的验证规则 value是用户输入的值 callback是回调函数
              if (value === "") {
                callback(new Error("密码长度6到16位"));
              } else if (value.length < 6 || value.length > 16) {
                callback(new Error("密码长度 6-16 位"));
              } else if (!checkSpecificKey(value)) {
                callback(new Error("密码不能包含特殊字符"));
              }
              //成功的回调
              callback();
            };
            return {
                loginForm: {
                    userAccount: "",
                    userPassword: ""
                  },
                rules: {
                    //验证用户名
                    userAccount: [
                      { required: true, message: "请输入账号", trigger: "blur" },
                      { min: 3, max: 18, message: "长度在18个字符", trigger: "blur" }
                    ],
                    //验证密码
                    userPassword: [
                      { required: true, validator: pass, trigger: "blur" } //validator 和确认密码做自定义验证
                    ]
                },
                checked: true,
                confirmInfo: false,
                user_name: '',
                user_number: ''
            };
        },
        created() {
            //如果已经登录过，就展示缓存的账号密码
            if (storage.contains("user")){
                let user = storage.get("user");
                console.log("已有用户数据，从缓存中获取");
                requestLogin({
                    params: {
                        userAccount: user.userAccount,
                        userPassword: user.userPassword
                    }
                }).then(req => {
                    //成功登录就跳转
                    this.intoIndex();
                });
            }
        },
        mounted() {
            this.getlocalStorage();
        },
        methods: {
            //登录
            submit() {
                //判断是否为游客登录
                if (isVisitorLogin(this.userAccount)) {
                    this.intoIndex();
                    return;
                }
                this.$refs.loginForm.validate(valid => {
                  if (valid) {
                    Toast.loading({
                      message: '登录中...',
                      forbidClick: true,
                    });
                    let params = {
                        userAccount: this.loginForm.userAccount,
                        userPassword: this.loginForm.userPassword
                    };
                  if (this.checked == true) {
                    this.setlocalStorage(this.loginForm.userAccount, this.loginForm.userPassword)
                  } else {
                    this.clearlocalStorage()
                  }
                  this.req.post("user/login",params).then(req => {
                    let { code,data,msg } = req;
                    // console.log(data);
                    if (code === 200) {
                        //设置token过期时间，过期以后将需要用户重新输入用户名和密码,默认在2小时以后，token自动失效7200000
                        localStorage.setItem('account',req.data.account);
                        localStorage.setItem('role',req.data.role);
                        localStorage.setExpire('token',msg,86400000);
                        Notify({ type: 'success', message: '登录成功' });
                        if (req.data.login_record == 0) {
                            this.confirmInfo = true;
                            var roles = req.data.role;
                            this.getStuInfo(roles);
                        }else{
                            this.intoIndex();
                        }
                        // this.intoIndex();
                        // this.confirmInfo = true;
                   } else {
                    // this.$message.error("登录失败,请重试...");
                    Notify({ type: 'danger', message: '登录失败,请重试...' });
                   }
                  });
                } else {
                console.log("error submit!!");
                return false;
              }
              });
            },
            intoIndex() {
                this.$router.push("/schedule")
            },
            cancel(){
                this.$router.push('/welcome')
            },
            // 像localStorage里存入从页面获取的用户名和密码；
            setlocalStorage(c_name, c_pwd) {
                localStorage.setExpire('userAccount',c_name,604800000);
                localStorage.setExpire('userPassword',c_pwd,604800000);
            },
            getlocalStorage() {
                // 获取带有过期时间的用户名和密码(前提是还没到过期时间)
                var source_acc = JSON.parse(localStorage.getItem('userAccount'));
                var source_pwd = JSON.parse(localStorage.getItem('userPassword'));
                if (source_acc) {
                    this.loginForm.userAccount = source_acc.token;
                }else{
                    return;
                }
                if (source_pwd) {
                    this.loginForm.userPassword = source_pwd.token;
                }else{
                    return;
                }   
            },
            // 点击忘记密码，清空localStorage里的存储
            clearlocalStorage() {
              localStorage.removeItem('userPassword');
            },
            // 关闭信息弹窗时触发
            async onBeforeClose(action, done) {
                if (action === 'confirm') {
                    // console.log(action);
                    // 点击确认信息按钮跳转到课程表
                    this.$router.replace('/schedule')
                }else{
                    return done(false);
                }
            },
            // 访问学生信息接口
            getStuInfo(role) {
                // let param = window.localStorage.getItem(account);
                const param = window.localStorage.getItem('account');
                if (role == 2) {
                    this.req.post("student/info",{account: param}).then(req => {
                    // let { code,data,msg } = req;
                    // console.log(req);
                    if (req.code === 200) {
                        this.user_name = req.data.stu_name;
                        this.user_number = req.data.stu_number;
                    } else {
                        Notify({ type: 'danger', message: '用户信息获取失败' });
                    }
                  });
                }
                if (role == 1) {
                    this.req.post("teacher/info",{account: param}).then(req => {
                    // let { code,data,msg } = req;
                    // console.log(req);
                    if (req.code === 200) {
                        this.user_name = req.data.stu_name;
                        this.user_number = req.data.stu_number;
                    } else {
                        Notify({ type: 'danger', message: '用户信息获取失败' });
                    }
                  });
                }
            }
        }
    }
</script>

<style scoped>
    .login-container {
        width: 100%;
        height: 100%;
    }

    .login-page {
        -webkit-border-radius: 5px;
        border-radius: 5px;
        margin: auto;
        padding: 35px 35px 15px;
        background: #fff;
        border: 1px solid #eaeaea;
        box-shadow: 0 0 25px #cac6c6;
        background: url("../images/Login_title.png") no-repeat ;
        background-size: 100% 100%;
    }

    .rememberme {
        margin: 0px 0px 15px;
        text-align: left !important;
    }

    .title_1 {
        text-align: left;
    }

    .title_2 {
        text-align: left;
    }
    .loginform {
        margin-top: 213px;
    }
    .userinfo {
        text-align: center;
    }
</style>
